package servlets;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//Try to use following code.... think you will get success.....

		String filename = "D:\\Reviews01.txt";
		
		ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( filename );

        File fileToDownload = new File(filename);
        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        response.setContentLength( (int)fileToDownload.length() );
        response.setHeader( "Content-Disposition", "attachment; filename=\"" + filename + "\"" );

		
//		response.setContentType("application/octet-stream");
//		String disHeader = "Attachment; Filename=\"filename\"";
//		response.setHeader("Content-Disposition", disHeader);

		InputStream in = null;
		ServletOutputStream outs = response.getOutputStream();

		try {
		in = new BufferedInputStream
		(new FileInputStream(fileToDownload));
		int ch;
		while ((ch = in.read()) != -1) {
		outs.print((char) ch);
		}
		}
		finally {
		if (in != null) in.close(); // very important
		}

		outs.flush();
		outs.close();
		in.close();
	}

}
